package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Stream;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User findByUsername(String username) {
        return userDao.findWithRolesByUsername(username);
    }

    @Override
    public void add(User user,Integer[] roleIds) {
        //保存用户基本信息
        userDao.add(user);
        if(roleIds != null){
            Integer userId = user.getId();
            //调用方法,将用户-角色对应关系一一存入
            setUserAndRole(userId,roleIds);
        }
    }

    //分页查询
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public Integer[] findRoleIdsAssociationIds(Integer userId) {
        return userDao.findRoleIdsAssociationIds(userId);
    }

    @Override
    public void update(User user, Integer[] roleIds) {
        //更新用户基本信息
        userDao.update(user);
        //删除用户角色关联表的信息
        userDao.deleteRoleIdsAssociation(user.getId());
        //添加新用户角色关联表的信息
        setUserAndRole(user.getId(),roleIds);
    }

    @Override
    public void delete(Integer userId) {
        //删除关联表信息
        userDao.deleteRoleIdsAssociation(userId);
        //删除用户基本信息
        userDao.delete(userId);
    }


    //将用户-角色按照关系一一存入
    private void setUserAndRole(Integer userId, Integer[] roleIds) {
        Stream.of(roleIds).forEach(roleId->userDao.setRoleAssociation(userId,roleId));
    }
}
